package demo.customer.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import demo.MyConfiguration;
import demo.model.AccountResponseModel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AccountService {
	
	@Autowired
	private MyConfiguration configuration;
	
    @Autowired
    @Qualifier("MyOAuth2RestTemplate")
    private RestTemplate restTemplate;
    
    @HystrixCommand(fallbackMethod = "getAccountsFallback",commandKey="account-service-hystrix")
    public AccountResponseModel getAccounts(String name, String region) {    	
    	
    	//log.info("****{}:getAccounts({},{}) is called ****",configuration.getServiceId(),name,region);
    	
    	return this.restTemplate.getForObject("http://account-service/account/list?name={name}&region={region}", AccountResponseModel.class,name,region);    	
    }
    
    @SuppressWarnings("unused")
	private AccountResponseModel getAccountsFallback(String name, String region, Throwable t) {
    	//note: t.getCause() == null for HystrixRuntimeException
    	if(t.getCause() != null) {
    		return new AccountResponseModel("account-service is unavailable [Cause:" + t.getCause().toString() +"]");  
    	}
    	    	
    	//log.error("****{}:getAccountsFallback({},{}) is called ****. Exception:{}",configuration.getServiceId(),name,region,t.toString());
    	
    	return new AccountResponseModel("account-service is unavailable [Exception:" + t.toString() +"]");  	
    }
}
